package com.mercenary.wein.screenControl.command;

import com.android.ddmlib.NullOutputReceiver;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
import com.mercenary.wein.screenControl.bean.CommandBean;
import com.mercenary.wein.screenControl.bean.DeviceBean;
import com.mercenary.wein.screenControl.bean.ExeModeBean;
import com.mercenary.wein.screenControl.dao.CommandDao;
import com.mercenary.wein.screenControl.deviceControll.AndroidDevice;
import com.mercenary.wein.screenControl.ui.MainFrame;
import com.mercenary.wein.screenControl.ui.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.*;

/**
 * Created by tuxiao on 2017/3/19.
 */
public class CommandTool {
    static Log log = LogFactory.getLog(CommandTool.class);
    static final String ACTION = "action";
    static final String NODETIME = "nodeTime";
    static CommandDao commandDao = new CommandDao();



    /**
     * 图片发朋友圈
     * @param dbs
     * @param files
     */
    public static void publishPic(List<DeviceBean> dbs,List<File> files,String content){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1001);
        json.put(NODETIME,1000);
        json.put("content",content);
        json.put("count",files.size());
        Set<String> filePaths = new HashSet<String>();
        for(File file:files){
            filePaths.add(file.getAbsolutePath());
        }
        String fps = Joiner.on("|").join(filePaths);
        for(DeviceBean db:dbs){
            CommandBean c = new CommandBean(1001,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setFilePaths(fps);
            commandBean.add(c);
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 点赞
     * @param dbs
     * @param count
     */
    public static void thumb(List<DeviceBean> dbs,int count,ExeModeBean exeModeBean){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1003);
        json.put(NODETIME,1000);
        json.put("count",count);
        long zid = new Date().getTime();//考虑到这是个单机系统，简单用时间戳来做id
        for(DeviceBean db:dbs){
            CommandBean c = new CommandBean(1003,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setExeModeBean(exeModeBean);
            c.setZid(zid);
            commandBean.add(c);
            if(exeModeBean.getMode()==1||exeModeBean.getMode()==2){//还需要加调度任务入库
                commandDao.insertScheduleTask(c);
            }
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 群发信息
     * @param dbs
     * @param message
     */
    public static void massMessage(List<DeviceBean> dbs,String message,List<File> files,ExeModeBean exeModeBean){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1004);
        json.put(NODETIME,1000);
        json.put("content",message);
        Set<String> filePaths = new HashSet<String>();
        for(File file:files){
//            String fileName = System.currentTimeMillis()+"-"+file.getName();
            filePaths.add(file.getAbsolutePath());
//            for(AndroidDevice ad:adbs){//这个应该是一个同步操作，会阻塞当前线程
//                ad.pushFile(file, Constants.DeviceFilePath+fileName);
//                ad.executeShellCommand("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://"+Constants.DeviceFilePath+fileName,new NullOutputReceiver());
//            }
        }
        String fps = Joiner.on("|").join(filePaths);
        long zid = new Date().getTime();//考虑到这是个单机系统，简单用时间戳来做id
        for(DeviceBean db:dbs){
            CommandBean c = new CommandBean(1004,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setExeModeBean(exeModeBean);
            c.setFilePaths(fps);
            c.setZid(zid);
            commandBean.add(c);
            if(exeModeBean.getMode()==1||exeModeBean.getMode()==2){//还需要加调度任务入库
                commandDao.insertScheduleTask(c);
            }
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 群发图片
     * @param dbs
     * @param adbs
     * @param file
     */
    public static void massPicture(List<DeviceBean> dbs,List<AndroidDevice> adbs ,File file){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        String fileName = file.getName()+System.currentTimeMillis();
        for(AndroidDevice ad:adbs){//这个应该是一个同步操作，会阻塞当前线程
            ad.pushFile(file, Constants.DeviceFilePath+fileName);
            ad.executeShellCommand("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://"+Constants.DeviceFilePath+fileName,new NullOutputReceiver());
        }
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1005);
        json.put(NODETIME,1000);
        json.put("fileName",fileName);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1005,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 模拟定位
     * @param dbs
     * @param lat
     * @param lon
     */
    public static void simulation(List<DeviceBean> dbs,double lat,double lon){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1006);
        json.put(NODETIME,1000);
        json.put("lat",lat);
        json.put("lon",lon);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1006,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 摇一摇
     * @param dbs
     * @param count
     */
    public static void shake(List<DeviceBean> dbs,int count,ExeModeBean exeModeBean){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1007);
        json.put(NODETIME,1000);
        json.put("count",count);
        long zid = new Date().getTime();//考虑到这是个单机系统，简单用时间戳来做id
        for(DeviceBean db:dbs){
            CommandBean c = new CommandBean(1007,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setExeModeBean(exeModeBean);
            c.setZid(zid);
            commandBean.add(c);
            if(exeModeBean.getMode()==1||exeModeBean.getMode()==2){//还需要加调度任务入库
                commandDao.insertScheduleTask(c);
            }
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 打招呼
     * @param dbs
     * @param count
     * @param gender
     * @param message
     */
    public static void sayHi(List<DeviceBean> dbs,int count,int gender,String message,ExeModeBean exeModeBean){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1009);
        json.put(NODETIME,1000);
        json.put("count",count);
        json.put("gender",gender);
        String[] mes = message.split("\n");
        int num = mes.length;
        Random random= new Random();
        long zid = new Date().getTime();//考虑到这是个单机系统，简单用时间戳来做id
        for(DeviceBean db:dbs){
            json.put("content",mes[random.nextInt(num)]);
            CommandBean c = new CommandBean(1009,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setExeModeBean(exeModeBean);
            c.setZid(zid);
            commandBean.add(c);
            if(exeModeBean.getMode()==1||exeModeBean.getMode()==2){//还需要加调度任务入库
                commandDao.insertScheduleTask(c);
            }
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 清理僵尸粉
     * @param dbs
     * @param message
     */
    public static void clearZombie(List<DeviceBean> dbs,String message,ExeModeBean exeModeBean){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1008);
        json.put(NODETIME,1000);
        String[] mes = message.split("\n");
        int num = mes.length;
        Random random= new Random();
        long zid = new Date().getTime();//考虑到这是个单机系统，简单用时间戳来做id
        for(DeviceBean db:dbs){
            json.put("content",mes[random.nextInt(num)]);
            CommandBean c = new CommandBean(1008,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setExeModeBean(exeModeBean);
            c.setZid(zid);
            commandBean.add(c);
            if(exeModeBean.getMode()==1||exeModeBean.getMode()==2){//还需要加调度任务入库
                commandDao.insertScheduleTask(c);
            }
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 添加通讯录好友
     * @param dbs
     * @param count
     */
    public static void addFriendFromAddressBook(List<DeviceBean> dbs, int count, ExeModeBean exeModeBean){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1010);
        json.put(NODETIME,1000);
        json.put("count",count);
        long zid = new Date().getTime();//考虑到这是个单机系统，简单用时间戳来做id
        for(DeviceBean db:dbs){
            CommandBean c =  new CommandBean(1010,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setExeModeBean(exeModeBean);
            c.setZid(zid);
            commandBean.add(c);
            if(exeModeBean.getMode()==1||exeModeBean.getMode()==2){//还需要加调度任务入库
                commandDao.insertScheduleTask(c);
            }
        }

        CommandPool.sendCommand(commandBean);
    }


    /**
     * 加群聊好友
     * @param dbs
     * @param count
     */
    public static void addFriendsFromMassChat(List<DeviceBean> dbs,int count,ExeModeBean exeModeBean){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1011);
        json.put(NODETIME,1000);
        json.put("count",count);
        long zid = new Date().getTime();//考虑到这是个单机系统，简单用时间戳来做id
        for(DeviceBean db:dbs){
            CommandBean c = new CommandBean(1011,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setExeModeBean(exeModeBean);
            c.setZid(zid);
            commandBean.add(c);
            if(exeModeBean.getMode()==1||exeModeBean.getMode()==2){//还需要加调度任务入库
                commandDao.insertScheduleTask(c);
            }
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 加搜索好友
     * @param dbs
     * @param name
     */
    public static void addFriendsFromSearch(List<DeviceBean> dbs,List<String> name,ExeModeBean exeModeBean){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1012);
        json.put(NODETIME,1000);
        json.put("contacts",name);
        long zid = new Date().getTime();//考虑到这是个单机系统，简单用时间戳来做id
        for(DeviceBean db:dbs){
            CommandBean c = new CommandBean(1012,new Gson().toJson(json),db.getSerialNo(),db.getPort());
            c.setExeModeBean(exeModeBean);
            c.setZid(zid);
            commandBean.add(c);
            if(exeModeBean.getMode()==1||exeModeBean.getMode()==2){//还需要加调度任务入库
                commandDao.insertScheduleTask(c);
            }
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 接受好友请求
     * @param dbs
     */
    public static void acceptAddRequest(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1013);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1013,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 接受附近的人打招呼
     * @param dbs
     */
    public static void acceptHi(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1014);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1014,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 接受摇一摇
     * @param dbs
     */
    public static void acceptShake(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1015);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1015,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 打开微信
     * @param dbs
     */
    public static void openWeChat(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1016);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1016,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 打开QQ
     * @param dbs
     */
    public static void openQQ(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1017);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1017,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 打开浏览器
     * @param dbs
     */
    public static void openIE(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1018);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1018,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 打开主界面
     * @param dbs
     */
    public static void openMainPage(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1019);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1019,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 打开飞行模式
     * @param dbs
     */
    public static void openFlyMode(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1020);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1020,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 关闭飞行模式
     * @param dbs
     */
    public static void closeFlyMode(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1021);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1021,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 打开手机屏幕
     * @param dbs
     */
    public static void openScreen(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1022);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1022,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }

    /**
     * 关闭手机屏幕
     * @param dbs
     */
    public static void closeScreen(List<DeviceBean> dbs){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1023);
        json.put(NODETIME,1000);
        for(DeviceBean db:dbs){
            commandBean.add(new CommandBean(1023,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
        }
        CommandPool.sendCommand(commandBean);
    }


    /**
     * 导入通讯录的方法
     * @param dbs
     * @param addressBook
     * @param ifClean 是否清空通讯录
     * @param mode 0-全部号码导入所有手机 1-平均导入每部手机 2-每部手机导入10个
     * @param num 每次导入的手机号数量
     * @return
     */
    public static void importAddressBook(List<DeviceBean> dbs, List<String> addressBook,boolean ifClean,int mode,int num){
        if(dbs.size()==0)return;
        List<CommandBean> commandBean = new ArrayList<CommandBean>();
        List<String> tmpAddressBook = new ArrayList<String>();
        Map<String,Object> json = new HashMap<String, Object>();
        json.put(ACTION,1025);
        json.put(NODETIME,1000);
        json.put("ifClean",ifClean);
        switch (mode){
            case 0 : {
                int i = 1;
                Iterator<String> it = addressBook.iterator();
                while(it.hasNext()){
                    if(i%50==0){
                        json.put("contacts",tmpAddressBook);
                        for(DeviceBean db : dbs){
                            commandBean.add(new CommandBean(1025,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
                        }
                        tmpAddressBook.removeAll(tmpAddressBook);
                    }
                    tmpAddressBook.add(it.next());
                    i++;
                }
                if(tmpAddressBook.size()>0){
                    json.put("contacts",tmpAddressBook);
                    for(DeviceBean db : dbs){
                        commandBean.add(new CommandBean(1025,new Gson().toJson(json),db.getSerialNo(),db.getPort()));
                    }
                }
                log.info("导入通讯录：共导入"+i+"个号码，模式：全部导入");
                break;
            }
            case 1 : {
                Map<String,Integer> deviceBeanMap = new HashMap<String, Integer>();
                Map<String,List<String>> addressMap = new HashMap<String, List<String>>();
                for(DeviceBean db:dbs){
                    deviceBeanMap.put(db.getSerialNo(),db.getPort());
                    addressMap.put(db.getSerialNo(),new ArrayList<String>());
                }
                Iterator<String> it = addressBook.iterator();
                z:{
                    while(true){
                        for(Map.Entry<String,List<String>> entry:addressMap.entrySet()){
                            if(!it.hasNext())break z;
                            entry.getValue().add(it.next());
                            if(entry.getValue().size()==50){
                                json.put("contacts",entry.getValue());
                                commandBean.add(new CommandBean(1025,new Gson().toJson(json),entry.getKey(),deviceBeanMap.get(entry.getKey())));
                                entry.getValue().removeAll(entry.getValue());
                            }
                        }
                    }
                }
                for(Map.Entry<String,List<String>> entry:addressMap.entrySet()){
                    json.put("contacts",entry.getValue());
                    commandBean.add(new CommandBean(1025,new Gson().toJson(json),entry.getKey(),deviceBeanMap.get(entry.getKey())));
                    entry.getValue().removeAll(entry.getValue());
                }
                break;
            }
            case 2:{
                int i = 1;
                Iterator<String> it = addressBook.iterator();
                Iterator<DeviceBean> dit = dbs.iterator();
                DeviceBean tmpDb=dit.next();
                z:{
                    while(it.hasNext()){
                        if(i%10==0){
                            json.put("contacts",tmpAddressBook);
                            commandBean.add(new CommandBean(1025,new Gson().toJson(json),tmpDb.getSerialNo(),tmpDb.getPort()));
                            tmpAddressBook.removeAll(tmpAddressBook);
                            if(dit.hasNext())tmpDb=dit.next();
                            else break z;
                        }
                        tmpAddressBook.add(it.next());
                        i++;
                    }
                }
                commandBean.add(new CommandBean(1025,new Gson().toJson(json),tmpDb.getSerialNo(),tmpDb.getPort()));
                break;
            }
        }
        CommandPool.sendCommand(commandBean);
    }


    public static void reboot(List<AndroidDevice> dbs){
        for(AndroidDevice adb:dbs){
            adb.executeShellCommand("reboot",new NullOutputReceiver());
        }
    }

    public static void shutdown(List<AndroidDevice> dbs){
        for(AndroidDevice adb:dbs){
            adb.executeShellCommand("reboot -p",new NullOutputReceiver());
        }
    }
}
